import { useToast } from '@/hooks/use-toast';
import { authClient } from '@/lib/auth-client';
import { zodResolver } from '@hookform/resolvers/zod';
import { useState } from 'react';
import { useForm } from 'react-hook-form';
import { z } from 'zod';
import { Button } from '../ui/button';
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogHeader,
  DialogTitle,
  DialogTrigger,
} from '../ui/dialog';
import {
  Form,
  FormControl,
  FormField,
  FormItem,
  FormLabel,
  FormMessage,
} from '../ui/form';
import { Input } from '../ui/input';

const userInfoSchema = z.object({
  name: z
    .string()
    .min(2, { message: '昵称至少2个字符' })
    .max(15, { message: '昵称最多15个字符' }),
});

export default function EditUserInfo() {
  const [open, setOpen] = useState(false);
  const { data: session } = authClient.useSession();
  const { toast } = useToast();
  const form = useForm<z.infer<typeof userInfoSchema>>({
    resolver: zodResolver(userInfoSchema),
    defaultValues: {
      name: session?.user.name ?? '',
    },
  });

  if (!session?.user) return null;

  const onSubmit = async (data: z.infer<typeof userInfoSchema>) => {
    const { error } = await authClient.updateUser(data);
    error
      ? toast({ title: error.message, variant: 'destructive' })
      : toast({ title: '更新成功' });
    if (!error) {
      setOpen(false);
      form.reset();
    }
  };

  return (
    <Dialog open={open}>
      <DialogTrigger asChild onClick={() => setOpen(true)}>
        <span className="i-ri-edit-line cursor-pointer absolute right-0" />
      </DialogTrigger>
      <DialogContent>
        <DialogHeader>
          <DialogTitle>编辑用户信息</DialogTitle>
          <DialogDescription className="hidden" />
        </DialogHeader>
        <Form {...form}>
          <form onSubmit={form.handleSubmit(onSubmit)} className="space-y-5">
            <FormField
              control={form.control}
              name="name"
              render={({ field }) => (
                <FormItem>
                  <FormLabel>昵称</FormLabel>
                  <FormControl>
                    <Input placeholder="昵称" {...field} />
                  </FormControl>
                  <FormMessage />
                </FormItem>
              )}
            />
            <div className="flex justify-between">
              <Button
                variant="ghost"
                type="button"
                onClick={() => {
                  setOpen(false);
                  form.reset();
                }}
              >
                取消
              </Button>
              <Button type="submit">保存</Button>
            </div>
          </form>
        </Form>
      </DialogContent>
    </Dialog>
  );
}
